package com.ssd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssd.constant.DkdContants;
import com.ssd.entity.*;
import com.ssd.mapper.NodeDao;
import com.ssd.mapper.RegionDao;
import com.ssd.mapper.VMDao;
import com.ssd.mapper.VMTypeDao;
import com.ssd.service.ChannelService;
import com.ssd.service.NodeService;
import com.ssd.service.VMService;
import com.ssd.service.VMTypeService;
import com.ssd.utils.DateUtils;
import com.ssd.utils.uuid.UUIDUtils;
import com.ssd.view.BaseResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class VMServiceImpl extends ServiceImpl<VMDao, VendingMachineEntity> implements VMService {

    @Autowired
    private VMDao vmDao;

    @Autowired
    private VMTypeDao vmTypeDao;

    @Autowired
    private RegionDao regionDao;

    @Autowired
    private NodeDao nodeDao;

    @Autowired
    private VMTypeService vmTypeService;

    @Autowired
    private NodeService nodeService;

    @Autowired
    private ChannelService channelService;

    /**
     * 分页查询商品列表，支持模糊查询
     *
     * @param pageNum  当前页码
     * @param pageSize 每页大小
     * @return 分页的商品集合
     */
    @Override
    public Page<VendingMachineEntity> getVMList(int pageNum, int pageSize, String innerCode) {
        // 创建分页对象
        Page<VendingMachineEntity> page = new Page<>(pageNum, pageSize);

        // 执行查询，这里假设 vmDao.selectVM 已经返回了 Page<VendingMachineEntity>
        Page<VendingMachineEntity> resultPage = vmDao.selectVM(page, innerCode);

        // 遍历分页结果集并为每个 vending machine entity 填充关联实体
        List<VendingMachineEntity> records = resultPage.getRecords();
        for (VendingMachineEntity vm : records) {
            populateRelatedEntities(vm);
        }

        return resultPage;
    }


    /**
     * 填充 VendingMachineEntity 的关联实体数据
     *
     * @param vm vending machine entity
     */
    private void populateRelatedEntities(VendingMachineEntity vm) {
        if (vm == null) {
            return;
        }

        // 查询并设置 VmTypeEntity
        Integer vmTypeId = vm.getVmType();
        if (vmTypeId != null) {
            VmTypeEntity vmType = vmTypeDao.selectById(vmTypeId);
            vm.setType(vmType);
        }

        // 查询并设置 NodeEntity
        Long nodeId = vm.getNodeId();
        if (nodeId != null) {
            NodeEntity node = nodeDao.selectById(nodeId);
            vm.setNode(node);
        }

        // 查询并设置 RegionEntity
        Long regionId = vm.getRegionId();
        if (regionId != null) {
            RegionEntity region = regionDao.selectById(regionId);
            vm.setRegion(region);
        }
    }

    /**
     * 根据主键查询商品详情
     *
     * @param vmId 商品主键
     * @return 商品详情
     */
    @Override
    public VendingMachineEntity selectVMByVMId(Long vmId) {
        VendingMachineEntity vm=vmDao.selectById(vmId);
        populateRelatedEntities(vm);
        return vm;
    }

    /**
     * 新增商品信息
     *
     * @return 影响的行数
     */
    @Override
    public int insertVM(VendingMachineEntity vendingMachine) {
        //1. 新增设备
        //1-1 生成8位的唯一标识，补充货道编号
        String innerCode = UUIDUtils.getUUID();
        vendingMachine.setInnerCode(innerCode);
        //1-2 查询售货机类型表，补充设备容量
        VmTypeEntity vmType = vmTypeService.selectVmTypeById(Long.valueOf(vendingMachine.getVmType()));
        vendingMachine.setType(vmType);
        //1-3 查询点位表，补充：区域、点位、合作商等信息
        NodeEntity node = nodeService.selectNodeById(vendingMachine.getNodeId());
        BeanUtil.copyProperties(node,vendingMachine,"id");// 商圈类型、区域、合作商
        vendingMachine.setNode(node);// 设备地址
        //1-4 设备状态
        vendingMachine.setVmStatus(DkdContants.VM_STATUS_NODEPLOY);// 0-表示未投放
        vendingMachine.setPolicyId(10);
        //1-5 保存
        int result = vmDao.insertVM(vendingMachine);
        //2. 新增货道
        //2-1 声明货道集合

        List<ChannelEntity> channelList = new ArrayList<>();
        //2-2 双层for循环
        for (int i = 1; i <=vmType.getVmRow() ; i++) {// 外层行
            for (int j = 1; j <=vmType.getVmCol() ; j++) {// 内层列
                // 1-1 1-2.. 2-1 2-2 ..
                //2-3 封层channel对象
                ChannelEntity channel = new ChannelEntity();
                channel.setChannelCode(i+"-"+j);// 货道编号
                channel.setVmId(vendingMachine.getId());// 售货机id
                channel.setInnerCode(vendingMachine.getInnerCode());// 售货机编号
                channel.setMaxCapacity(vmType.getChannelMaxCapacity());// 货道最大容量
                channel.setCurrentCapacity(vmType.getChannelMaxCapacity());// 货道当前容量
                channelList.add(channel);
            }
        }
        //2-4 批量保存
        channelService.batchInsertChannels(channelList);
        return result;
    }

    /**
     * 修改商品信息
     *
     * @param vm 更新后的商品实体
     * @return 影响的行数
     */
    @Override
    public int updateVM(VendingMachineEntity vm) {
        return vmDao.updateById(vm);
    }

    /**
     * 批量删除商品信息
     *
     * @param vmIds 需要删除的商品主键数组
     * @return 影响的行数
     */
    @Override
    public int deleteVMByVMIds(Long[] vmIds) {
        return vmDao.deleteBatchIds(java.util.Arrays.asList(vmIds));
    }

    /**
     * 删除指定ID的商品信息
     *
     * @param vmId 商品主键
     * @return 影响的行数
     */
    @Override
    public int deleteVMByVMId(Long vmId) {
        return vmDao.deleteById(vmId);
    }

    //根据id查询商品
    @Override
    public BaseResponse<VendingMachineEntity> getVMById(Long sukId) {
        VendingMachineEntity vm=baseMapper.selectById(sukId);
        return new BaseResponse (vm);
    }

    // 根据商品id集合查询vm列表
    @Override
    public List<VendingMachineEntity> getVMsByIds(List<Long> vmIds) {
        return baseMapper.selectBatchIds(vmIds);
    }
}